package com.jumi.microservice.service.invoice.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.dto.invoice.*;
import com.jumi.microservice.service.invoice.invoiceConfig.InvoiceConfig;
import com.jumi.microservice.utils.nuonuo.QueryThirdCommonRequest;
import com.jumi.microservice.entity.JumiInvoice;
import com.jumi.microservice.entity.JumiInvoiceList;
import com.jumi.microservice.enumerate.InvoiceStatusEnum;
import com.jumi.microservice.mapper.InvoiceListMapper;
import com.jumi.microservice.mapper.InvoiceMapper;
import com.jumi.microservice.service.*;
import com.jumi.microservice.service.invoice.InvoiceApiService;
import com.jumi.microservice.utils.NuoNuoUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Administrator
 */
@DubboService(interfaceClass = IWalletInvoiceService.class)
public class InvoiceServiceImpl implements IWalletInvoiceService {
    private static final Logger log = LoggerFactory.getLogger(InvoiceServiceImpl.class);
    @Resource
    private InvoiceMapper invoiceMapper;
    @Resource
    private InvoiceListMapper invoiceListMapper;

    @Resource
    private InvoiceApiService invoiceApiService;
    @Resource
    private NuoNuoUtil nuoNuoUtil;
    @Autowired
    InvoiceConfig invoiceConfig;

    /**
     * 订单发票状态修改
     *
     * @param invoiceStatusRequest
     * @return
     */
    @Override
    public Boolean invoiceEditStatus(InvoiceStatusRequest invoiceStatusRequest) {
        String invoiceNum = invoiceStatusRequest.getOrderNum();
        if (invoiceNum == null) {
            return null;
        }
        QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.orderByDesc("id");
        invoiceQueryWrapper.eq("order_num", invoiceStatusRequest.getOrderNum());
        invoiceQueryWrapper.eq("is_revoke", 0);
        /*取出最新一条数据*/
        invoiceQueryWrapper.last("limit 1");
        JumiInvoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        log.info("订单发票状态修改对外提供接口------【取出最新一条数据】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            return false;
        }
        invoice.setInvoiceStatus(invoiceStatusRequest.getInvoiceStatus());
        int row = invoiceMapper.update(invoice, invoiceQueryWrapper);

        // 第三方直接开票
        InvoiceOneRequest request = new InvoiceOneRequest();
        request.setOrderNum(invoiceStatusRequest.getOrderNum());
        invoiceApiService.invoice(request);
        return row > 0;
    }

    /**
     * 根据订单编号查询订单发票id
     *
     * @param orderId
     * @return
     */
    @Override
    public Integer invoiceOneStatus(Integer orderId) {
        QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.eq("order_id", orderId);
        invoiceQueryWrapper.orderByDesc("id");
        invoiceQueryWrapper.last("limit 1");
        JumiInvoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        return invoice == null ? 0 : invoice.getId();
    }


    /**
     * 根据订单编号查询发票列表----列表页
     *
     * @param invoiceOrderSnListRequest
     * @return
     */
    @Override
    public TableDataInfo<InvoiceOrderSnListResponse> invoiceListOrder(InvoiceOrderSnListRequest invoiceOrderSnListRequest) {
        String orderSn = invoiceOrderSnListRequest.getOrderNum();
        if (orderSn == null) {
            return null;
        }
        QueryWrapper<JumiInvoice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_num", orderSn);
        queryWrapper.orderByDesc("id");
        List<JumiInvoice> invoice = invoiceMapper.selectList(queryWrapper);
        log.debug("根据订单编号查询发票列表外提供接口------【列表页】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            return null;
        }
        List<InvoiceOrderSnListResponse> result = new ArrayList<>();
        for (JumiInvoice invoice2 : invoice) {
            InvoiceOrderSnListResponse invoiceOrderSnListResponse = new InvoiceOrderSnListResponse();
            BeanUtils.copyProperties(invoice2, invoiceOrderSnListResponse);
            result.add(invoiceOrderSnListResponse);
        }
        TableDataInfo<InvoiceOrderSnListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        return dataInfo;
    }

    /**
     * ruiguang提交发票专用,传值包含开票金额
     *
     * @param invoiceAddRequest
     * @return
     */
    @Override
    public Integer addOrderInvoice(InvoiceAddRequest invoiceAddRequest) {
        Long uid = invoiceAddRequest.getUid();
        if (uid == null) {
            return null;
        }
        Integer invoiceId = invoiceAddRequest.getInvoiceId();
        JumiInvoice invoice = new JumiInvoice();
        if (invoiceId == null || invoiceId.equals(0)) {
            invoice.setInvoiceTitle("个人");
            invoice.setOrderId(invoiceAddRequest.getOrderId());
            invoice.setOrderNum(invoiceAddRequest.getOrderNum());
            invoice.setInvoiceType((byte) 0);
            invoice.setHeadType((byte) 0);
            invoice.setBankDeposit("");
            invoice.setBankAccount("");
            invoice.setBusinessAddress("");
            invoice.setEnterpriseTel("");
            invoice.setDutyParagraph("");
            invoice.setInvoiceAmount(invoiceAddRequest.getInvoiceAmount());
            invoice.setInvoiceId(invoiceId);
            invoice.setDutyParagraph("");
            invoice.setInvoiceStatus((byte) 6);
        } else {
            //查询该抬头id
            QueryWrapper<JumiInvoiceList> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", invoiceId);
            JumiInvoiceList invoiceListOne = invoiceListMapper.selectOne(queryWrapper);
            if (invoiceListOne == null) {
                return null;
            }
            invoice.setInvoiceTitle(invoiceListOne.getInvoiceTitle());
            invoice.setHeadType(invoiceListOne.getHeadType());
            invoice.setBankDeposit(invoiceListOne.getBankDeposit());
            invoice.setBankAccount(invoiceListOne.getBankAccount());
            invoice.setBusinessAddress(invoiceListOne.getBusinessAddress());
            invoice.setEnterpriseTel(invoiceListOne.getEnterpriseTel());
            invoice.setOrderId(invoiceAddRequest.getOrderId());
            invoice.setOrderNum(invoiceAddRequest.getOrderNum());
            invoice.setInvoiceAmount(invoiceAddRequest.getInvoiceAmount());
            invoice.setDutyParagraph(invoiceListOne.getDutyParagraph());
            invoice.setInvoiceId(invoiceId);
        }
        invoiceMapper.insert(invoice);
        return invoice.getId();
    }

    @Override
    public InvoiceOneResponse getInvoice(InvoiceOneRequest request) {
        InvoiceOneResponse invoiceOneResponse = new InvoiceOneResponse();
        String orderSn = request.getOrderNum();
        if (orderSn == null) {
            invoiceOneResponse.setId(0);
            invoiceOneResponse.setInvoiceStatus((byte) -1);
            return invoiceOneResponse;
        }
        QueryWrapper<JumiInvoice> invoiceQueryWrapper = new QueryWrapper<>();
        invoiceQueryWrapper.orderByDesc("id");
        invoiceQueryWrapper.eq("order_num", orderSn);
        invoiceQueryWrapper.eq("is_revoke", 0);
        /*取出最新一条数据*/
        invoiceQueryWrapper.last("limit 1");
        JumiInvoice invoice = invoiceMapper.selectOne(invoiceQueryWrapper);
        log.info("根据订单编号查询订单发票状态是否已开票外提供接口------【取出最新一条数据】:[{}]", JSON.toJSONString(invoice));
        if (invoice == null) {
            invoiceOneResponse.setId(0);
            invoiceOneResponse.setInvoiceStatus((byte) -1);
            return invoiceOneResponse;
        }
        /*传递信息*/
        invoiceOneResponse.setInvoiceStatus(invoice.getInvoiceStatus());
        invoiceOneResponse.setId(invoice.getId());
        return invoiceOneResponse;
    }

    @Scheduled(cron = "0 0/3 * * * *")
    public void invoiceTimingTask() {

        updateInvoicePdf();

        updateRedInvoice();
    }

    public void updateRedInvoice() {
        QueryWrapper<JumiInvoice> jumiInvoiceQueryWrapper = new QueryWrapper<>();
        jumiInvoiceQueryWrapper.lambda().eq(JumiInvoice::getIsRevoke, 0).eq(JumiInvoice::getInvoiceStatus, InvoiceStatusEnum.STA_WAIT_REDDDMED.getCode());
        List<JumiInvoice> jumiInvoices = invoiceMapper.selectList(jumiInvoiceQueryWrapper);
        for (JumiInvoice jumiInvoice : jumiInvoices) {
            QueryThirdCommonRequest request = new QueryThirdCommonRequest();
            request.setIdentity(invoiceConfig.getIdentity());
            request.setFpqqlsh(jumiInvoice.getRedSerialNumber());
            String result = nuoNuoUtil.QueryInvoice(request);
            log.info("定时任务修改发票pdf"+result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray jsonElements = jsonObject.getJSONArray("list");
            if (jsonElements == null) {
                jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.RED_INVOICE_FAILURE.getCode().byteValue());
                invoiceMapper.updateById(jumiInvoice);
                continue;
            }
            for (Object o : jsonElements) {
                if (((JSONObject) o).getString("c_status").equals("2")) {
                    jumiInvoice.setRedInvoicePdf(((JSONObject) o).getString("c_url"));
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.STA_HAS_REDDDMED.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                } else if (((JSONObject) o).getString("c_status").equals("22")) {
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.RED_INVOICE_FAILURE.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                } else if (((JSONObject) o).getString("c_status").equals("26")) {
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.RED_INVOICE_FAILURE.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                } else {
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.RED_INVOICE_FAILURE.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                }
            }
        }
    }

    public void updateInvoicePdf() {
        log.info("进入定时任务");
        QueryWrapper<JumiInvoice> jumiInvoiceQueryWrapper = new QueryWrapper<>();
        jumiInvoiceQueryWrapper.lambda().eq(JumiInvoice::getIsRevoke, 0).eq(JumiInvoice::getInvoiceStatus, InvoiceStatusEnum.STA_WAIT_BILLED.getCode());
        List<JumiInvoice> jumiInvoices = invoiceMapper.selectList(jumiInvoiceQueryWrapper);
        log.info("定时任务数据是[{}]",JSON.toJSONString(jumiInvoices));
        for (JumiInvoice jumiInvoice : jumiInvoices) {
            QueryThirdCommonRequest request = new QueryThirdCommonRequest();
            request.setIdentity(invoiceConfig.getIdentity());
            request.setFpqqlsh(jumiInvoice.getSerialNumber());
            log.info("查询定时任务参数是[{}]",JSON.toJSONString(request));
            String result = nuoNuoUtil.QueryInvoice(request);
            log.info("定时任务修改发票pdf[{}]",result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray jsonElements = jsonObject.getJSONArray("list");
            if (jsonElements == null) {
                log.info("定时任务走了JsonElements==null");
                jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.INVOICE_FAILURE.getCode().byteValue());
                invoiceMapper.updateById(jumiInvoice);
                continue;
            }
            for (Object o : jsonElements) {
                if (((JSONObject) o).getString("c_status").equals("2")) {
                    jumiInvoice.setInvoicePdf(((JSONObject) o).getString("c_url"));
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.STA_HAS_BILLED.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                } else if (((JSONObject) o).getString("c_status").equals("22")) {
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.INVOICE_FAILURE.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                } else if (((JSONObject) o).getString("c_status").equals("26")) {
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.INVOICE_FAILURE.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                } else {
                    jumiInvoice.setInvoiceStatus(InvoiceStatusEnum.INVOICE_FAILURE.getCode().byteValue());
                    invoiceMapper.updateById(jumiInvoice);
                }
            }
        }
    }

}
